/***************************************************************************
 创建者：华磊
 开始时间：         : 2020.12.08
 copyright            : (C) 深圳市华友高科有限公司
 修改说明：（每次有修改就添加一条，带有 修改人，修改时间，修改描述）

 ***************************************************************************
 *   运动指令属性编辑视窗
*                                                                         *
 ***************************************************************************/
#include "motioninstructionview.h"
#include "ui_motioninstructionview.h"
#include "../../programView/programview.h"
//#define D_MAX_AXIS_COUNT 50

extern FileData fileData;

MotionInstructionView::MotionInstructionView(int styleId,GlobalData *ioDataIn, QWidget *parent):
    QWidget(parent),
    ui(new Ui::MotionInstructionView)
{
    ioData=ioDataIn;
    ui->setupUi(this);

    motionInstruction2View = new MotionInstruction2View(styleId);
    motionInstruction2View->motionInstructionView = this;

    this->setGeometry(5,50,431,544);
    initialDisplayStyle(styleId);

    //pointPro = new PointPro;
    model = new QStandardItemModel;
    ui->pointData_tableView_2->setModel(model);
    model->setColumnCount(2);
    ui->pointData_tableView_2->setColumnWidth(0,155);//410-30 = 380
    ui->pointData_tableView_2->setColumnWidth(1,225);

    ui->pointData_tableView_2->verticalHeader()->hide();

    //点位数值限制
    //ui->position_lineEdit_2->setValidator(new QIntValidator(1, 999, this));
    ui->pointData_tableView_2->horizontalHeader()->setVisible(false);

    patternRR = "^\\s*R\\[R\\[(\\d+)\\]\\]\\s*$";
    patternR = "^\\s*R\\[(\\d+)\\]\\s*$";
    patternC = "^\\s*(\\d+)\\s*$";

    //
    lockBtnText = tr("点已解锁");
    lockBtnPicture = "color: rgb(255, 255, 255); border-width:0px;border-style:outset;image: url(/agvwork/AgvHmi/baseBag/hmiProject/resources/instruction/MotionInstructionRes/empty_n.png);";

    setViewText();
}

void MotionInstructionView::initialDisplayStyle(int styleId)
{
    switch (styleId) {
    case 1:
        ui->pointData_GBox->setGeometry(10,95,430,245);
        ui->pointData_tableView_2->setGeometry(10,20,410,195);
        ui->takeEffect_Btn->setGeometry(70,215,110,30);
        ui->turnToJoint_Btn->setGeometry(190,215,110,30);
        ui->turnToDiKa_Btn->setGeometry(310,215,110,30);
        ui->rate_GBox->setGeometry(10,340,340,58);

        ui->next_Btn->setGeometry(360,350,70,40);
        break;
    default:
        break;
    }
}

void MotionInstructionView::updateViewPointData()
{
    model->clear();
    QString str = "";
    int type = pointProMo.jointFlag;
    if(type == EM_CF_DEG_TYPE)
    {
        str = tr("关节点");
        ui->pointData_GBox->setTitle(tr("点数据:当前类型 关节点"));
    }
    else if(type == EM_CF_WORLD_TYPE)
    {
        str = tr("笛卡尔点");
        ui->pointData_GBox->setTitle(tr("点数据:当前类型 笛卡尔点"));
    }

    model->setHeaderData(0,Qt::Horizontal,tr("类型"));
    model->setHeaderData(1,Qt::Horizontal,tr("值"));
    model->setItem(0,0,new QStandardItem(tr("节点类型")));
    model->setItem(0,1,new QStandardItem(tr("")));
    model->item(0,1)->setEditable(false);
    model->setItem(1,0,new QStandardItem(tr("点编号")));
    model->setItem(1,1,new QStandardItem(tr("")));
    model->item(1,1)->setEditable(false);
    model->setItem(2,0,new QStandardItem(tr("组编号")));
    model->setItem(2,1,new QStandardItem(tr("")));
    model->item(2,1)->setEditable(false);
    model->setItem(3,0,new QStandardItem(tr("用户坐标系编号")));
    model->setItem(3,1,new QStandardItem(tr("")));
    model->item(3,1)->setEditable(false);
    model->setItem(4,0,new QStandardItem(tr("工具坐标系编号")));
    model->setItem(4,1,new QStandardItem(tr("")));
    model->item(4,1)->setEditable(false);
    model->setItem(5,0,new QStandardItem(tr("多解选择;多圈选择")));
    model->setItem(5,1,new QStandardItem(tr("")));
    model->item(5,1)->setEditable(false);
//    model->setItem(6,0,new QStandardItem(tr("J1")));//1
//    model->setItem(7,0,new QStandardItem(tr("EX1")));
//    for(int i=0;i<D_MAX_AXIS_COUNT;i++)
//    {
//        model->setItem(8+i,0,new QStandardItem(""));//J1
//    }


//    for(int i = 0;i<8+D_MAX_AXIS_COUNT;i++)
//    {
//        model->setItem(i,1,new QStandardItem(""));
//        model->item(i,0)->setEditable(false);
//    }

 //   sixAxisName.clear();
    if(6 != sixAxisName.size())
    {
        sixAxisName.resize(6);
        sixAxisName[0] = tr("轴值:X");
        sixAxisName[1] = tr("轴值:Y");
        sixAxisName[2] = tr("轴值:Z");
        sixAxisName[3] = tr("轴值:W");
        sixAxisName[4] = tr("轴值:P");
        sixAxisName[5] = tr("轴值:R");
    }

    model->item(0,1)->setText(str);
    model->item(0,1)->setEditable(false);

    str = QString::number(pointProMo.pointNum);
    model->item(1,1)->setText(str);
    model->item(1,1)->setEditable(false);

    str = QString::number(pointProMo.groupNum);
    model->item(2, 1)->setText(str);

    str = QString::number(pointProMo.ufValue  );//
    model->item(3, 1)->setText(str);

    str = QString::number(pointProMo.utValue  );
    model->item(4, 1)->setText(str);

    str = QString::fromStdString(pointProMo.configString);
    //qDebug()<<"====*==pointProMo.configString==="<<str;
    model->item(5, 1)->setText(str);


    int size=pointProMo.positionValue.size();
    for(int i=0;i<size;i++)
    {
        model->setItem(6+i,0,new QStandardItem(tr("")));
        model->setItem(6+i,1,new QStandardItem(tr("")));
        QString line=QString::number(pointProMo.positionValue[i]);
        if(EM_CF_DEG_TYPE == type)
        {
            model->item(6+i,0)->setText(tr("轴值:J")+QString::number(i+1));
            model->item(6+i,1)->setText(line);
        }
        else
        {
            if( i<6 )
            {
                model->item(6+i,0)->setText(sixAxisName[i]);
                model->item(6+i,1)->setText(line);
            }
        }


    }

//    QString total2 = "";
//    size=pointProMo.extPositionValue.size();
//    for(int i=0;i<size ;i++)
//    {
//        QString line=QString::number(pointProMo.extPositionValue[i]);
//        total2=line+"; "+total2;
//    }
//    rowNum++;//+1
//    model->item(rowNum,0)->setText(tr("外部轴值"));
//    model->item(rowNum,1)->setText(total2);

//    for(int i=0;i<pointProMo.extPositionValue.size();i++)
//    {
//        rowNum++;//+1
//        //qDebug()<<rowNum<<" *** "<<pointProMo.extPositionValue[i];
//        model->item(rowNum,0)->setText(tr("外部轴值:E")+QString::number(i+1));
//        model->item(rowNum,1)->setText(QString::number(pointProMo.extPositionValue[i]));
//    }

//    rowNum++;
//    if(rowNum<18)
//    {
//        for(int i = rowNum;i<18;i++)
//        {
//            model->item(i,0)->setText("");
//            model->item(i,1)->setText("");
//        }
//    }

    ui->pointData_tableView_2->setModel(model);
    ui->pointData_tableView_2->setColumnWidth(0,155);//410-30 = 380
    ui->pointData_tableView_2->setColumnWidth(1,225);
    if(size>0)
    {
        QModelIndex nextIndex = model->index(6, 0);
        ui->pointData_tableView_2->scrollTo(nextIndex,QAbstractItemView::PositionAtTop);
    }

}

void MotionInstructionView::updateView()
{

    ui->C_radioButton_2->setEnabled(false);
    ui->J_radioButton_2->setEnabled(false);
    ui->L_radioButton_2->setEnabled(false);
    ui->A_radioButton_2->setEnabled(false);

    //先判断是普通的运动还是冲压专用的运动
    if(EM_INSTRUCTION_NORMAL == instructionMainFlag)
    {
        ui->C_radioButton_2->show();
        ui->J_radioButton_2->show();
        ui->L_radioButton_2->show();
        ui->A_radioButton_2->show();

        //
        ui->position_comboBox_2->setEnabled(true);
        ui->rateUnit_comboBox_2->setEnabled(true);
    }
    else
    {
        ui->A_radioButton_2->hide();
        ui->C_radioButton_2->hide();

        //
        ui->position_comboBox_2->setEnabled(false);//不可选 P PR
        ui->rateUnit_comboBox_2->setEnabled(false);//不可选 单位
    }

    //单选框
    if(E_MOTION_J == instructionTypeFlag)
    {
        ui->J_radioButton_2->setEnabled(true);
        ui->L_radioButton_2->setEnabled(true);
        ui->J_radioButton_2->setChecked(true);
    }
    else if(E_MOTION_L == instructionTypeFlag)
    {
        ui->J_radioButton_2->setEnabled(true);
        ui->L_radioButton_2->setEnabled(true);
        ui->L_radioButton_2->setChecked(true);
    }
    else if((E_MOTION_C == instructionTypeFlag) || (E_MOTION_C2 == instructionTypeFlag))//EM_INSTRUCTION_TYPE_C_2
    {
        ui->C_radioButton_2->setEnabled(true);
        ui->C_radioButton_2->setChecked(true);
    }
    else if(E_MOTION_A == instructionTypeFlag)
    {
        ui->A_radioButton_2->setEnabled(true);
        ui->A_radioButton_2->setChecked(true);
    }

    //P PR 点编号
    ui->position_comboBox_2->setCurrentIndex(positionTypeFlag);
    qDebug()<<"positionIndexStr="<<positionIndexStr;


    ui->combox_palletIndex->setCurrentIndex(moIns.palNum-1);


    //先载入一个"",然后才能触发下面的;因为存在一种情况,如果打开了1
    //下一个也是1,那么将会不触发
    ui->position_lineEdit_2->setText("");
    ui->position_lineEdit_2->setText(positionIndexStr);//同步触发 textChangeSLot

    //qDebug()<<"lockBtnPicture="<<lockBtnPicture;

    //点锁定状态
    int index = pointProMo.pointNum -1;
    if(index >=0 && index < fileData.normalPointLock.size() )//PR可能存在没有载入的情况 index<0
    {
        qDebug()<<fileData.normalPointLock;
        qDebug()<< index <<":"<<fileData.normalPointLock[index];
        if(fileData.normalPointLock[index])
        {
            lockBtnText = tr("点已锁定");
            lockBtnPicture = "color: rgb(255, 255, 255); border-width:0px;border-style:outset;image: url(/agvwork/AgvHmi/baseBag/hmiProject/resources/instruction/MotionInstructionRes/empty_d.png);";
        }
        else
        {
            lockBtnText = tr("点已解锁");
            lockBtnPicture = "color: rgb(255, 255, 255); border-width:0px;border-style:outset;image: url(/agvwork/AgvHmi/baseBag/hmiProject/resources/instruction/MotionInstructionRes/empty_n.png);";
        }
    }
    else
    {
        lockBtnText = tr("点已解锁");
        lockBtnPicture = "color: rgb(255, 255, 255); border-width:0px;border-style:outset;image: url(/agvwork/AgvHmi/baseBag/hmiProject/resources/instruction/MotionInstructionRes/empty_n.png);";
    }
    //点锁状态
    ui->lockPoint_Btn_2->setText(lockBtnText);
    ui->lockPoint_Btn_2->setStyleSheet(lockBtnPicture);//set 背景图片



    //百分比
    ui->rate_lineEdit_2->setText(QString("%1").arg(instructionRate));
    ui->rateUnit_comboBox_2->setCurrentIndex(rateUnitTypeFlag);
    ui->rate_slider_2->setSliderPosition(instructionRate);

    //第二个页面的内容也需要更新
    motionInstruction2View->updateView();
}

void MotionInstructionView::getInput()
{
    //第一页
    positionIndexStr = ui->position_lineEdit_2->text();
    instructionRate = ui->rate_lineEdit_2->text().toFloat();
    rateUnit = ui->rateUnit_comboBox_2->currentText();
    moIns.palNum=ui->combox_palletIndex->currentIndex()+1;

    if(E_MOTION_J == instructionTypeFlag)
    {
        emit setDefaultJMoveSpeed_signal(instructionRate);
    }
    else
    {
        emit setDefaultLMoveSpeed_signal(instructionRate,rateUnit);
    }



    //第二页
    motionInstruction2View->getInput();


    switch(positionTypeFlag)
    {
    case E_POSITION_P:
    {
       positionTypeStr="P";
       positionIndexAddressStr=positionIndexStr;
       break;
    }
    case E_POSITION_PR:
    {
       positionTypeStr="PR";
       positionIndexAddressStr=positionIndexStr;
       break;
    }
    case E_POSITION_PAL_A:
    {
        positionTypeStr="PAL_"+ QString::number(moIns.palNum);
        positionIndexAddressStr="A_"+positionIndexStr;
        break;
    }
    case E_POSITION_PAL_R:
    {
        positionTypeStr="PAL_"+ QString::number(moIns.palNum);
        positionIndexAddressStr="R_"+positionIndexStr;
        break;
    }
    case E_POSITION_PAL_BTM:
    {
        positionTypeStr="PAL_"+ QString::number(moIns.palNum);
        positionIndexAddressStr="BTM";
        break;
    }


    }
}

void MotionInstructionView::getInputPointData()
{
    QString strData;
    int intData;

    QAbstractItemModel *model = ui->pointData_tableView_2->model();
    QModelIndex index = model->index(0, 0);
    //intData = model->data(index).toInt();
    //pointProMo.jointFlag = intData;//类型//禁止获取

    index = model->index(1, 1);
    intData = model->data(index).toInt();
    pointProMo.pointNum = intData;//点编号

    index = model->index(2, 1);
    intData = model->data(index).toInt();
    pointProMo.groupNum = intData;//组编号

    index = model->index(3, 1);
    intData = model->data(index).toInt();//实际用户看到的要减去1
    pointProMo.ufValue = intData;//用户坐标编号

    index = model->index(4, 1);
    intData = model->data(index).toInt();
    pointProMo.utValue = intData;//工具坐标编号

    index = model->index(5, 1);
    strData = model->data(index).toString();
    pointProMo.configString = strData.toStdString();//多圈

//    index = model->index(6, 0);
//    strData = model->data(index).toString();
//    if(strData != "")
//    {
//        QStringList strList = strData.split(",");
//        qDebug()<<"strList.size() = "<<strList.size();
//        pointProMo.configInt.resize(strList.size()-1);
//        for(int i = 0; i < strList.size()-1 ; i++)//待定处理方法 -1
//        {
//            pointProMo.configInt[i] = strList[i].toInt();
//            qDebug()<<__FUNCTION__<<" "<<i<<" "<<pointProMo.configInt[i];
//        }
//    }

    //2017.02.16 index(8 + i, 0) → index(7 + i, 0)
    for(int i = 0; i < pointProMo.positionValue.size(); i++)
    {
        index = model->index(6 + i, 1);
        float data = model->data(index).toFloat();
        pointProMo.positionValue[i] = data;
        qDebug()<<__FUNCTION__<<" "<<i<<" "<<pointProMo.positionValue[i];
    }

    //model->deleteLater();//补充删除指针 不知道为何不能删除
}

void MotionInstructionView::on_next_Btn_clicked()
{
    this->close();
    motionInstruction2View->show();
}


void MotionInstructionView::on_J_radioButton_2_clicked()
{
    emit selectJInstruction();
}

void MotionInstructionView::on_L_radioButton_2_clicked()
{
    emit selectLInstruction();
}

void MotionInstructionView::on_rate_slider_2_sliderMoved(int position)
{
    instructionRate = position;
    ui->rate_lineEdit_2->setText(QString::number(instructionRate));
}

void MotionInstructionView::on_lockPoint_Btn_2_clicked()
{
    emit unlockPoint();
}

void MotionInstructionView::on_recordPoint_Btn_2_clicked()
{
    int number = getRrgToIndex(ui->position_lineEdit_2->text());
    if(number > 0 )
    {
        emit recordPoint_signal(positionTypeFlag,number);//2017.03.21 补充P PR类型
    }
}

void MotionInstructionView::on_moveToPoint_Btn_2_pressed()
{
    int number = getRrgToIndex(ui->position_lineEdit_2->text());
    if(number > 0 )
    {
        emit moveToPointSignal(positionTypeFlag,number);//2017.03.21 补充P PR类型
    }
}

void MotionInstructionView::on_moveToPoint_Btn_2_released()
{
    emit moveToPointFinish();
}

void MotionInstructionView::on_takeEffect_Btn_clicked()
{
    getInputPointData();//获取输入点数据

    emit inputPointTakeEffect();//跟新
}

void MotionInstructionView::on_rate_slider_2_valueChanged(int value)
{
    instructionRate = value;
    ui->rate_lineEdit_2->setText(QString::number(instructionRate));
}

void MotionInstructionView::on_turnToJoint_Btn_clicked()
{
    int number = getRrgToIndex(ui->position_lineEdit_2->text());
    if(number > 0 )
    {
        emit changePointToDeg(number);
    }
}

void MotionInstructionView::on_turnToDiKa_Btn_clicked()
{
    int number = getRrgToIndex(ui->position_lineEdit_2->text());
    if(number > 0 )
    {
        emit changePointToWorld(number);
    }
}

void MotionInstructionView::on_position_lineEdit_2_textChanged(const QString &arg1)
{
    std::vector<PointPro> pointRegisterOut;
    ioData->getPointRegister(pointRegisterOut);
    if(arg1 != "")
    {
        //qDebug()<<"change point";
        int index = 0;

        index = getRrgToIndex(arg1);//获取R的实际值

        qDebug()<<"motion point number="<<index;

        if(E_POSITION_P == positionTypeFlag)       //P
        {
            if(index>0 && index <= fileData.getPointProList.size())
            {
                pointProMo = fileData.getPointProList[index-1];
            }
            else
            {
                if(index == 0)
                {
                    emit msgBoxSignal(EM_MSG_BOX_SURE_BTN,tr("提示"),tr("P点编号为0\n禁止使用不存在的编号"));
                    pointProMo.positionValue.clear();
                }
                else if(index == -10)
                {
                    pointProMo.positionValue.clear();
                }
                else
                {
//                    emit msgBoxSignal(EM_MSG_BOX_SURE_BTN,tr("提示"),tr("P点没有载入数据\n请点击载入点"));
                    pointProMo.positionValue.clear();
                }

            }
        }
        else if(E_POSITION_PR == positionTypeFlag)                  //PR
        {
            if(index>0 && index <= pointRegisterOut.size())
            {
                pointProMo = pointRegisterOut[index-1];
            }
            else
            {
                if(index == 0)
                {
                    emit msgBoxSignal(EM_MSG_BOX_SURE_BTN,tr("提示"),tr("PR点编号为0\n禁止使用不存在的编号"));
                    pointProMo.positionValue.clear();
                }
                else if(index == -10)
                {
                    pointProMo.positionValue.clear();
                }
            }

        }
        else
        {
            pointProMo.positionValue.clear();
        }

        //刷新页面
        updateViewPointData();
    }
}

void MotionInstructionView::on_position_lineEdit_2_editingFinished()
{
    QString arg1 = ui->position_lineEdit_2->text();

    QRegExp rxRR(patternRR);
    QRegExp rxR(patternR);
    QRegExp rxC(patternC);
    int posC = arg1.indexOf(rxC);
    int posR = arg1.indexOf(rxR);
    int posRR = arg1.indexOf(rxRR);

    if(posC < 0 && posR < 0 && posRR < 0)
    {
        emit msgBoxSignal(EM_MSG_BOX_SURE_BTN,tr("提示"),tr("当前输入的点格式不正确\n请及时修改"));
    }
}

void MotionInstructionView::setViewText()
{


    lockBtnText = tr("点已解锁");
}

int MotionInstructionView::getRrgToIndex(QString arg1)
{
    qDebug()<<"getRrgToIndex arg1 = "<<arg1;
    std::vector<double > registerOut;
    ioData->getLocalRegister(registerOut);
    int index = 0;
    //QRegExp rxRR(patternRR);//暂时不需要
    QRegExp rxR(patternR);
    QRegExp rxC(patternC);

    int posC = arg1.indexOf(rxC);
    int posR = arg1.indexOf(rxR);
    //int posRR = arg1.indexOf(rxRR);

    //if(posC >= 0 || posR >= 0 || posRR >= 0)
    if(posC >= 0 || posR >= 0)
    {
        if(posC >= 0)
        {
            index = rxC.cap(1).toInt();
            return index;
        }
        if(ioData)
        {
//            ioData->lock();
            if(posR >= 0)
            {
                index = rxR.cap(1).toInt();
                if(index>0 && index<=registerOut.size())
                {
                    index = registerOut[index - 1];
//                    ioData->unlock();
                    return index;
                }
                else
                {
//                    ioData->unlock();
                    return 0;
                }
            }
//            if(posRR >= 0)
//            {
//                index = rxRR.cap(1).toInt();
//                if(index>0 && index<=ioData->localRegister.size())
//                {
//                    index = ioData->localRegister[index - 1];
//                    if(index>0 && index<=ioData->localRegister.size() )
//                    {
//                        index = ioData->localRegister[index - 1];
//                        ioData->unlock();
//                        return index;
//                    }
//                    else
//                    {
//                        ioData->unlock();
//                        return 0;
//                    }
//                }
//            }
        }
    }
    else
    {
//        ioData->unlock();
        return -10;
    }

//    ioData->unlock();
    return -10;
}

void MotionInstructionView::on_position_comboBox_2_currentIndexChanged(int index)
{
//    getInput();
    qDebug()<<index;
    if(positionTypeFlag != index)
    {
        positionTypeFlag = index;
//        positionIndexStr = ui->position_lineEdit_2->text();
//        ui->position_lineEdit_2->setText("");//为了使textChange可以被触发
//        updateView();
    }


}

void MotionInstructionView::changeLanguage(int language)
{
    if(1 == language)
    {
        translator.load("/agvwork/AgvHmi/baseBag/hmiProject/language/motionViewEnglishLan.qm");
        qApp->installTranslator(&translator);
    }
    else
    {
        qApp->removeTranslator(&translator);
    }
    ui->retranslateUi(this);

    setViewText();

    motionInstruction2View->changeLanguage();
}
